package com.dstz.org.core.manager.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dstz.base.api.exception.BusinessError;
import com.dstz.base.api.exception.BusinessException;
import com.dstz.base.api.exception.BusinessMessage;
import com.dstz.base.api.query.QueryFilter;
import com.dstz.base.core.encrypt.EncryptUtil;
import com.dstz.base.core.util.AppUtil;
import com.dstz.base.core.util.StringUtil;
import com.dstz.base.manager.impl.BaseManager;
import com.dstz.org.core.constant.RelationTypeConstant;
import com.dstz.org.core.dao.UserDao;
import com.dstz.org.core.manager.OrgRelationManager;
import com.dstz.org.core.manager.UserCreditRecordManager;
import com.dstz.org.core.manager.UserManager;
import com.dstz.org.core.model.OrgRelation;
import com.dstz.org.core.model.User;
import com.dstz.org.core.model.UserCreditRecord;
import com.dstz.sys.api.constant.EnvironmentConstant;
import com.dstz.sys.util.ContextUtil;

import cn.hutool.core.collection.CollectionUtil;

/**
 * <pre>
 * 描述：用户表 处理实现类
 * </pre>
 */
@Service("userManager")
public class UserManagerImpl extends BaseManager<String, User> implements UserManager {
    @Resource
    UserDao userDao;
    @Resource
    OrgRelationManager orgRelationMananger;
    @Resource
    UserCreditRecordManager userCreditRecordManager;

    public User getByAccount(String account) {
        return this.userDao.getByAccount(account);
    }

    @Override
    public boolean isUserExist(User user) {
        return userDao.isUserExist(user)>0;
    }

	@Override
	public List<User> getUserListByRelation(String relId, String type) {
		if(type.equals(RelationTypeConstant.POST_USER.getKey())) {
			OrgRelation postRelation = orgRelationMananger.get(relId);
			if(postRelation == null) return Collections.emptyList();
			return userDao.getUserListByPost(postRelation.getGroupId(),postRelation.getUserId());
		}
		
		return userDao.getUserListByRelation(relId,type);
	}
	
	/**
	 * 通过ID 获取会带上用户关系信息
	 */
	@Override
	public User get(String entityId) {
		
		User user =  super.get(entityId);
		if(user!= null) {
			user.setOrgRelationList(orgRelationMananger.getUserRelation(entityId, null));
		}
		return user;
	}
	
	@Override
	public void remove(String entityId) {
		orgRelationMananger.removeByUserId(entityId);
		super.remove(entityId);
	}

	@Override
	public void saveUserInfo(User user) {
		if(StringUtil.isEmpty(user.getId())) {
			if(StringUtil.isEmpty(user.getPassword())) {
				user.setPassword("1");
			}
            user.setPassword(EncryptUtil.encryptSha256(user.getPassword()));
            user.setCredit(0l);
			this.create(user);
		}else {
			user.setPreVersion(user.getVersion());
			user.setCredit(null);
			Integer update = userDao.update(user);
			if(update<=0) {
				throw new BusinessException("版本号过期，请重试");
			}
			orgRelationMananger.removeByUserId(user.getId());
		}
		
		List<OrgRelation> orgRelationList = user.getOrgRelationList();
		if(CollectionUtil.isEmpty(orgRelationList)) return;
		
		orgRelationList.forEach( rel ->{
			rel.setUserId(user.getId());
			orgRelationMananger.create(rel);
		});
		 
	}

	@Override
	public List<User> getBirthDayMonthUsers(QueryFilter queryFilter) {
		Date date=new Date();
		queryFilter.addParamsFilter("birthDay", date);
		List<User> query = userDao.query(queryFilter);
		for (User user : query) {
			if(user!= null) {
				user.setOrgRelationList(orgRelationMananger.getUserRelation(user.getId(), null));
			}
		}
		return query;
	}
	
	@Override
	public User getCurrentUser() {
		String currentUserId = ContextUtil.getCurrentUserId();
		User user =  super.get(currentUserId);
		if(user!= null) {
			user.setOrgRelationList(orgRelationMananger.getUserRelation(currentUserId, null));
		}
		return user;
	}

	@Override
	@Transactional
	public void updateCredit(String userId, long credit,String remark) {
		User user = userDao.get(userId);
		if(user==null) throw new BusinessException("用户不存在");
		user.setPreVersion(user.getVersion());
		long credit2 = user.getCredit()==null?0l:user.getCredit();
		long postCredit = credit2+credit;
		if(postCredit<0) throw new BusinessMessage("用户积分不足");
		user.setCredit(postCredit);
		Integer update = userDao.update(user);
		if(update<=0) {
			throw new BusinessException("版本号过期，请重试");
		}
		UserCreditRecord userCreditRecord=new UserCreditRecord();
		userCreditRecord.setCreditBalance(postCredit);
		userCreditRecord.setCreditChange(credit);
		userCreditRecord.setRemark(remark);
		userCreditRecord.setUserId(userId);
		userCreditRecordManager.create(userCreditRecord);
	}

	@Override
	public void updateUserPsw(String oldPassWorld, String newPassword, String userId) {
		if(!userId.equals(ContextUtil.getCurrentUserId())) {
        	throw new BusinessException("禁止修改他人密码！");
        }
        
        if(AppUtil.getCtxEnvironment().contains(EnvironmentConstant.SIT.key())) {
       	 throw new BusinessError("测试环境为了防止不法之徒恶意破坏演示数据，禁止修改密码！<br/>您的访问信息已经被我们统计！");
        }
        User user = this.get(ContextUtil.getCurrentUserId());
        if (!user.getPassword().equals(EncryptUtil.encryptSha256(oldPassWorld))) {
            throw new BusinessMessage("旧密码输入错误");
        }
        user.setPreVersion(user.getVersion());
        user.setPassword(EncryptUtil.encryptSha256(newPassword));
        user.setCredit(null);
        Integer update = userDao.update(user);
		if(update<=0) {
			throw new BusinessException("版本号过期，请重试");
		}
	}
}
